document.addEventListener('DOMContentLoaded', function() {
    const form = document.getElementById('upload-form');
    const fileInput = document.getElementById('file-input');
    const progressBar = document.getElementById('progress-bar');
    const progress = document.getElementById('progress');
    const message = document.getElementById('message');

    form.addEventListener('submit', function(e) {
        e.preventDefault();

        const file = fileInput.files[0];
        if (!file) {
            message.textContent = '请选择一个文件';
            return;
        }

        const formData = new FormData();
        formData.append('file', file);

        progressBar.style.display = 'block';
        message.textContent = '';

        fetch('/upload', {
            method: 'POST',
            body: formData
        })
        .then(response => response.json())
        .then(data => {
            message.textContent = data.message;
            progressBar.style.display = 'none';
        })
        .catch(error => {
            console.error('Error:', error);
            message.textContent = '上传失败，请重试';
            progressBar.style.display = 'none';
        });
    });

    // 模拟上传进度
    function simulateProgress() {
        let width = 0;
        const interval = setInterval(() => {
            if (width >= 100) {
                clearInterval(interval);
            } else {
                width++;
                progress.style.width = width + '%';
            }
        }, 50);
    }

    fileInput.addEventListener('change', function() {
        message.textContent = '';
    });

    form.addEventListener('submit', simulateProgress);
});